package com.market.utils;

import com.market.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import java.util.Enumeration;

/**
 * Session工具类，用于获取当前登录用户信息
 */
public class SessionUtil {
    private static final Logger logger = LoggerFactory.getLogger(SessionUtil.class);

    /**
     * 用户信息存储在session中的key
     */
    public static final String USER_SESSION = "userSession";
    
    /**
     * 获取当前登录用户
     * @return 当前登录用户对象，如果未登录则返回null
     */
    public static User getCurrentUser() {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes == null) {
                logger.warn("RequestContextHolder.getRequestAttributes() 返回 null");
                return null;
            }
            
            HttpServletRequest request = attributes.getRequest();
            logRequestDetails(request);
            
            HttpSession session = request.getSession(false);
            if (session == null) {
                logger.warn("当前没有可用的session");
                return null;
            }
            
            logSessionDetails(session);
            
            User user = (User) session.getAttribute(USER_SESSION);
            if (user == null) {
                logger.warn("session中没有用户信息");
            } else {
                logger.info("成功获取到当前登录用户: {}, ID: {}", user.getUserName(), user.getId());
            }
            return user;
        } catch (Exception e) {
            logger.error("获取当前用户信息出错", e);
            return null;
        }
    }
    
    /**
     * 记录请求的详细信息
     */
    private static void logRequestDetails(HttpServletRequest request) {
        logger.info("=== 请求详情 ===");
        logger.info("请求URL: {}", request.getRequestURL());
        logger.info("请求方法: {}", request.getMethod());
        logger.info("请求来源: {}", request.getRemoteAddr());
        logger.info("ContentType: {}", request.getContentType());
        logger.info("请求是否有session: {}", (request.getSession(false) != null));
        
        // 记录请求头信息
        logger.info("=== 请求头信息 ===");
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            logger.info("{}:{}", headerName, request.getHeader(headerName));
        }
        
        // 记录Cookie信息
        logger.info("=== Cookie信息 ===");
        jakarta.servlet.http.Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (jakarta.servlet.http.Cookie cookie : cookies) {
                logger.info("Cookie名称:{}, 值:{}, 域:{}, 路径:{}, 最大年龄:{}", 
                    cookie.getName(), cookie.getValue(), cookie.getDomain(), 
                    cookie.getPath(), cookie.getMaxAge());
            }
        } else {
            logger.warn("没有发现Cookie");
        }
    }
    
    /**
     * 记录session的详细信息
     */
    private static void logSessionDetails(HttpSession session) {
        logger.info("=== Session详情 ===");
        logger.info("Session ID: {}", session.getId());
        logger.info("创建时间: {}", new java.util.Date(session.getCreationTime()));
        logger.info("最后访问时间: {}", new java.util.Date(session.getLastAccessedTime()));
        logger.info("最大不活动间隔: {}秒", session.getMaxInactiveInterval());
        
        logger.info("=== Session属性 ===");
        Enumeration<String> attributeNames = session.getAttributeNames();
        while (attributeNames.hasMoreElements()) {
            String attributeName = attributeNames.nextElement();
            logger.info("属性名:{}, 值类型:{}", attributeName, 
                session.getAttribute(attributeName) != null ? 
                session.getAttribute(attributeName).getClass().getName() : "null");
        }
    }
    
    /**
     * 获取当前登录用户ID
     * @return 当前登录用户ID，如果未登录则返回null
     */
    public static Long getCurrentUserId() {
        User currentUser = getCurrentUser();
        if (currentUser == null) {
            logger.warn("当前没有登录用户，返回null用户ID");
            return null;
        }
        logger.info("获取到当前登录用户ID: {}", currentUser.getId());
        return currentUser.getId();
    }
} 